package com.springboot.cloud.demos.web.controller;

import com.springboot.cloud.common.core.entity.vo.Result;
import com.springboot.cloud.demos.entity.form.CouponForm;
import com.springboot.cloud.demos.entity.param.CouponQueryParam;
import com.springboot.cloud.demos.entity.po.Coupon;
import com.springboot.cloud.demos.web.service.CouponService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
public class CouponController {
    @Autowired
    private CouponService couponService;

    @GetMapping("/coupon/list")
    public String coupon(Model model) {
        CouponQueryParam params = new CouponQueryParam();
        Result result = couponService.conditions(params);
        if (result.isSuccess()) {
            model.addAttribute("coupons", result.getData());
        }
        return "coupon/list";
    }

    @GetMapping("/coupon/delete")
    public String delete(Model model, String id) {
        couponService.delete(id);
        CouponQueryParam params = new CouponQueryParam();
        Result result = couponService.conditions(params);
        if (result.isSuccess()) {
            model.addAttribute("coupons", result.getData());
        }
        return "coupon/list";
    }

    @GetMapping("/coupon/input")
    public String input(String id, Model model) {
        Result result;
        if (StringUtils.isNotEmpty(id)) {
            result = couponService.coupon(id);
            model.addAttribute("coupon", result.getData());
            model.addAttribute("isEdit", "edit");
        } else {
            model.addAttribute("coupon", new Coupon());
            model.addAttribute("isEdit", "add");
        }
        return "coupon/input";
    }

    @RequestMapping(value = "/coupon/save", method = RequestMethod.POST)
    @ResponseBody
    public Result save(CouponForm couponForm) {
        if (StringUtils.isNotEmpty(couponForm.getId())) {
            return couponService.update(couponForm);
        }
        return couponService.add(couponForm);
    }


}
